package com.lion.seaman.common;


import com.lion.seaman.common.tools.StringTools;
import org.apache.log4j.Logger;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class LoadJs {
    static Logger log = Logger.getLogger(LoadJs.class);

    public static <T> T load(String basePath, String scriptPath) throws ScriptException, NoSuchMethodException {
        String path = basePath.concat(scriptPath);
        String eval = "load(\"{0}\")";
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
        try {
            //加载常规配置
            File commonFile = new File(basePath.concat("/common/common.js"));
            if (commonFile.exists()) {
                nashorn.eval(new FileReader(commonFile));
            }
        } catch (IOException e) {
            log.error("load common file has error:" + e.getMessage(), e);
        }
        if (path.contains("#")) {
            nashorn.eval(StringTools.format(eval, path.split("#")[0]));
            Invocable invocable = (Invocable) nashorn;
            return (T) invocable.invokeFunction(path.split("#")[1]);
        } else {
            return (T) nashorn.eval(StringTools.format(eval, path));
        }
    }

}
